
import { Dimensions } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage'
import _ from './BaseTools'
import IP from './../http/host'

/**
 * ! JS代码 工具类：处理JSON.parse，处理字符串，对象等
 *
 */
const CodeTools = {
    // 常量值
    getScreen: Dimensions.get('screen'),

    /**
     * 判断函数
     * @param {Function} fun 函数名
     * @returns {boolean}
     */
    isFunction: (fun) => fun instanceof Function,

    isDev: () => IP.server_ip !== 'http://114.55.135.153:8000',

    /**
     * * 处理 SearchBar 组件回传值
     *
     * @param {*} items
     * @param {string} items.key 模板标识
     * @param {string} items.name 选项卡名称
     * @param {string} items.title 选项卡提示名称
     * @param {string} items.type 模板类型
     * @param {number} items.rangeType 模板类型
     * @param {{name:string,value:string}} items.value 选中值
     * @param {{name:string,value:string}[]} items.data 模板数据
     * @returns {object}
     */
    buildSearchItem: (items = []) => items.reduce((result, _) => {
        result[_.key] = _.value
        return result
    }, {}),

    /**
     * * 数字|字符串 补位
     * ? Example 1: 99  =>  0099
     * ? Example 2: 66  =>  6600
     *
     * @param {object} config 配置项
     * @param {number|string} config.source 原数据
     * @param {number} config.len 长度
     * @param {string} [config.place] 占位符
     * @param {boolean} [config.leftToRight] 补位方向
     * @returns {string}
     */
    padStr(config) {
        const { source, len, place = " ", leftToRight = true } = config
        const temp = source.toString()
        return leftToRight ? temp.padStart(len, place) : temp.padEnd(len, place)
    },

    /**
     * * 树结构字段转换自定义
     * * Example:
     * ?    source = [{name:'A',value:'1',tree:[{name:'AA',value:'11',tree:[]}]}]
     * ?    sourceKey = 'tree'
     * ?    childKey = 'children'
     * ?    map = {title:'name',age:'value'}
     *
     * ?    [{name:'A',value:'1',tree:[{name:'AA',value:'11',tree:[]}]}]
     * ?    =>   [{title:'A',age:'1',children:[{title:'AA',age:'11',children:[]}]}]
     *
     * @param {any} source 元数据
     * @param {string} sourceKey 后代段名
     * @param {string} childKey 自定义后代名
     * @param {any} map 转换表
     * @returns {any[]}
     */
    transformTreeToSelf: (source, sourceKey, childKey, map) => {
        let temp = {}, result = []
        source.forEach(element => {
            for (const _key in map) {
                temp[_key] = element[map[_key]]
            }
            if (element?.[sourceKey]?.length) {
                temp[childKey] = Utils.transformTreeToSelf(element[sourceKey], sourceKey, childKey, map)
            }
            result.push(temp)
            temp = {}
        });
        return result
    },

    /**
     * * 处理数组
     * ? Example 提取值: [{name:'A'},{name:'B'}] => ['A','B']
     * ? Example 重构属性: [{name:'A', key:'1'},{name:'B', key:'2'}] => [{value:'A'},{value:'B'}]
     *
     * @param {any[]} source 元数据
     * @param {string} sourceKey 目标字段名
     * @param {string} [targetKey] 存储字段名
     * @returns {string[]|Object[]}
     */
    getArrayByKey: (source = [], sourceKey = "", targetKey = "") => {
        if (targetKey) {
            return source.reduce((result, _) => result.push({ [targetKey]: _[sourceKey] }) && result, [])
        } else {
            return source.reduce((result, _) => result.push(_[sourceKey]) && result, [])
        }
    },

    /**
     * * 快捷弹框
     *
     * @param {string|object} content 提示信息
     * @param {number=1} buttonLen 长度
     * @param {string='小智提醒'} title 标题
     * @param {object} config 配置项
     * @param {string='确认'} config.confirmButton 自定义确认按钮
     * @param {string='取消'} config.cancelButton 自定义取消按钮
     * @param {string='取消'} config.otherButton 自定义按钮
     * @returns
     */
    showModal: (content, buttonLen = 1, title = '小智提醒', config = {}) =>
        new Promise(resolve => {
            const button = []
            if (buttonLen >= 2) {
                button.push({
                    text: config.cancelButton || '取消',
                    onPress: () => {
                        resolve([true, undefined])
                    }
                })
            }
            if (buttonLen >= 1) {
                button.push({
                    text: config.confirmButton || '确认',
                    onPress: () => {
                        resolve([undefined, true])
                    }
                })
            }
            if (buttonLen >= 3) {
                button.push({
                    text: config.otherButton || '取消',
                    onPress: () => {
                        resolve([undefined, undefined, true])
                    }
                })
            }
            alert(title, typeof content === 'string' ? content : _.showMessage(content), button, config)
        })
    ,

    /**
    *
    * @param {string} str - JSON字符串
    * @returns {[undefined|Error, any|undefined]}
    */
    toJson(str) {
        try {
            return [undefined, JSON.parse(str)]
        } catch (e) {
            return [e, undefined]
        }
    },

    /**
     * * 设置本地存储
     *
     * @param {string} cacheKey 键名
     * @param {any} any 存储值
     * @returns {Promise<[null|undefined,string|undefined]>}
     */
    setLocalStore: async (cacheKey, any) => await _.to(AsyncStorage.setItem(cacheKey, typeof any === 'string' ? any : JSON.stringify(any))),

    /**
     * * 获取本地存储
     *
     * @param {string} cacheKey 键名
     * @returns {Promise<[null|undefined,string|undefined]>}
     */
    getLocalStore: async (cacheKey) => await _.to(AsyncStorage.getItem(cacheKey)),

    /**
     * * 删除本地存储值
     *
     * @param {string} cacheKey 键名
     * @returns {Promise<[null|undefined,string|undefined]>}
     */
    deleteLocalStore: async (cacheKey) => await _.to(AsyncStorage.removeItem(cacheKey)),

    /**
     * * 获取本地所有键
     *
     * @returns {Promise<[null|undefined,string|undefined]>}
     */
    getLocalStoreAllKeys: async () => await _.to(AsyncStorage.getAllKeys()),
}

export default CodeTools
